const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const Client = require('../schema/Client')
const Admin = require('../schema/Admin')
const crypto = require('crypto')
const tools = require('../utils/tools')
const config = require('../config')

const userRouter = new Router({
  prefix: '/nodeApi/user'
})

userRouter.post('/login', async ctx => {
  let loginUser = ctx.request.body.loginUser,
      password = ctx.request.body.password;
  if (tools.isEmpty(loginUser) || tools.isEmpty(password)) {
    ctx.status = 400;
    ctx.body = {
      result: 'fail',
      message: '缺少账号或密码'
    }
    return;
  } else {
    // md5 + salt
    password = crypto.createHash('md5').update(password + config.secret).digest('hex')
    let user = await Client.findOne({ loginUser: loginUser });
    if (!user || user.password !== password) {
      ctx.status = 400;
      ctx.body = {
        result: 'fail',
        message: '账号或密码错误'
      }
    } else {
      let payload = {
        opCode: user.opCode,
        opName: user.opName
      }
      let token = jwt.sign(payload, config.secret, { expiresIn: 36000000, algorithm: 'HS512' });
      ctx.body = {
        result: 'success',
        token: token,
        userInfo: user
      }
    }
  }
})
userRouter.post('/admin/login', async ctx => {
  let loginUser = ctx.request.body.loginUser,
      password = ctx.request.body.password;
  if (tools.isEmpty(loginUser) || tools.isEmpty(password)) {
    ctx.status = 400;
    ctx.body = {
      result: 'fail',
      message: '缺少账号或密码'
    }
    return;
  } else {
    // md5 + salt
    password = crypto.createHash('md5').update(password + config.secret).digest('hex')
    let admin = await Admin.findOne({ loginUser: loginUser });
    if (!admin || admin.password !== password) {
      ctx.status = 400;
      ctx.body = {
        result: 'fail',
        message: '账号或密码错误'
      }
    } else {
      let payload = {
        opCode: admin.opCode,
        opName: admin.opName
      }
      let token = jwt.sign(payload, config.secret, { expiresIn: 36000000, algorithm: 'HS512' });
      ctx.body = {
        result: 'success',
        token: token,
        opCode: admin.opCode,
        opName: admin.opName
      }
    }
  }
})

module.exports = userRouter